package cn.itsource.service.impl;

import cn.itsource.enums.Sex;
import cn.itsource.mapper.UserMapper;
import cn.itsource.pojo.User;
import cn.itsource.pojo.bo.UserBO;
import cn.itsource.service.UserService;
import cn.itsource.utils.DateUtil;
import cn.itsource.utils.MD5Utils;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.io.Serializable;
import java.util.Date;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    private static final String USER_FACE = "https://note.youdao.com/yws/public/resource/8e8917947ff57c8c8ea367fb70fd07c4/xmlnote/50C45023A7D5456A9546F185FE7AB368/7078";

    /**
     * 判断用户名是否存在
     * @param username
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public boolean queryUsernameIsExist(String username) {

        Example userExample = new Example(User.class);
        Example.Criteria criteria = userExample.createCriteria();
        criteria.andEqualTo("username",username);

        User result = userMapper.selectOneByExample(userExample);

        return result == null ? false : true;
    }

    /**
     * 注册用户
     * @param userBO
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public User createUser(UserBO userBO) {
        // 把UserBo 转换为数据库映射 User
        User user = new User();
        user.setUsername(userBO.getUsername());
        user.setNickname(userBO.getUsername());         // 默认用户名与昵称相同

        // MD5加密的密码
        try {
            user.setPassword(MD5Utils.getMD5Str(userBO.getPassword()));
        } catch (Exception e) {
            e.printStackTrace();
        }

        //  idworker 雪花算法
        user.setId(Sid.next());
        // 默认生日
        user.setBirthday(DateUtil.stringToDate("1900-01-01"));
        // 默认头像
        user.setFace(USER_FACE);
        // 默认保密
        user.setSex(Sex.secret.type);

        user.setCreatedTime(new Date());
        user.setUpdatedTime(new Date());

        userMapper.insert(user);

        return user;
    }

    /**
     * 用户登录
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public User queryUserForLogin(String username ,String password) {

        return userMapper.findOneByUsernameAndPassword(username,password);
    }
}
